#include"my_stdio.h"

_FILE* my_fopen(const char* pathname,const char* mode){
    int flags = 0;
    int open_mode = 0666;
    if(strcmp(mode,"r")==0){
        flags |= O_RDONLY;
    }else if(strcmp(mode,"w")==0){
        flags |= O_WRONLY|O_TRUNC|O_CREAT;
    }else if(strcmp(mode,"a") == 0){
        flags |= O_WRONLY|O_APPEND|O_CREAT;
    }
    int fd = 0;
    if(flags & O_RDONLY)    fd = open(pathname,flags);
    else fd = open(pathname,flags,open_mode);
    
    if(fd == -1){
        const char* err = strerror(errno);
        write(2,err,strlen(err));
        return NULL;
    }

    _FILE* fl = (_FILE*)malloc(sizeof(_FILE));
    fl->fileno = fd;
    fl->capacity = SIZE;
    fl->flag = LINE_REFRESH;
    fl->size = 0;
    memset(fl->buffer,0,SIZE);
    return fl;
    
}

void fflush(_FILE* file){
    if(file->size > 0) write(file->fileno,file->buffer,file->size);
}
int my_fwrite(void* buff,int num, _FILE* file){
    //first copy in buffer, then if refresh
    memcpy(file->buffer,buff,num);
    file->size = num;

    if(file->flag & NOW_REFRESH){
        fflush(file);
        file->size = 0;
    } 
    else if(file->flag & FULL_REFRESH){
        if(file->capacity == file->size){
            fflush(file);
            file->size = 0;
        }
    }else if(file->flag & LINE_REFRESH){
        if(file->buffer[file->size-1] == '\n') {
            fflush(file);
            file->size = 0;
        }
    }
    return num;
}


int my_fclose(_FILE* file){
    fflush(file);
    return close(file->fileno);
}